global class NoContractApplicationBatch implements Database.Batchable<NoContractInstrumentApplicationDetail__c> {

    global NoContractApplicationBatch() {
    }

    global Iterable<NoContractInstrumentApplicationDetail__c> start(Database.batchableContext info){
        Datetime d = Datetime.valueOf('2020-01-15 00:00:00');
       return [select Id, ExpectedProcessingTime__c, WhetherNotice__c,NoContractInstrumentApplication__r.Owner.Name ,
        NoContractInstrumentApplication__r.Owner.IsActive , 
       NoContractInstrumentApplication__r.OwnerId ,ExpectedProcessingWay__c  from  NoContractInstrumentApplicationDetail__c where  
       ExpectedProcessingTime__c <: System.today() and WhetherNotice__c != true and CreatedDate >=:d  and NoContractInstrumentApplication__r.stage__c = '已批准' and WhetherFinishe__c != true ];

    }

    
    //离职了发给用户档案上的上级呗 --- 文

    global void execute(Database.BatchableContext BC, List< NoContractInstrumentApplicationDetail__c> scope) {
       
        List<Task> tmp =new List<Task>();
        Map<Id,User> userMap =new Map<Id,User >();
        for (NoContractInstrumentApplicationDetail__c nod   :scope ) {
            if(nod.NoContractInstrumentApplication__r.Owner.IsActive == false ) userMap.put(nod.NoContractInstrumentApplication__r.OwnerId,null);
            nod.WhetherNotice__c = true ;
            
        }
        for (User u  : [select Id,ManagerId,Manager.Name   from User where Id in: userMap.keySet() ]) {
            userMap.put(u.Id  , u);
        }
        for ( NoContractInstrumentApplicationDetail__c nod   :scope ) {
            String owId = nod.NoContractInstrumentApplication__r.OwnerId ;
            String userName  = userMap.containsKey(owId) ? userMap.get(owId).Manager.Name  : nod.NoContractInstrumentApplication__r.Owner.Name;
            owId = userMap.containsKey(owId) ? userMap.get(owId).ManagerId : owId;

            Task t = new Task();
            String msg = userName + '你好！你提交的无销售合同明细选择的处理方式为：'+nod.ExpectedProcessingWay__c  +'，预计处理时间为：'+nod.ExpectedProcessingTime__c+'，目前已经到期，请尽快完成合同签订或者上传仪器签收确认单！';
            t.Subject = msg ;
            t.OwnerId  = owId ;
            t.Description = msg  ;
            t.WhatId = nod.Id;
            t.ActivityDate = System.today();
            tmp.add(t);
        }

        update scope;
        if(!tmp.isEmpty())insert tmp;

    }

    global void finish(Database.BatchableContext BC) {

    }
}